// 定义mui
mui.init();

// 公共变量
var userlogin = null; // 用户登录信息
var dataDomain = "http://101.200.201.27/adm/kkdata/kap/"; // 后端数据接口host
// var dataDomain = "http://localhost/kap/"; // 后端数据接口host


var picker_choose_gym = function(){
	// 设置门店三连选工具
	// 设置区域，城市，门店三级联动下拉选项
	$.get(dataDomain + 'gyms.php', {do: 'getGymRegions'}, function(data){
		console.log(data);
	
		if(userlogin && userlogin.user_type == 12){ // 城市经理一级，可以看到所属大区所有城市
			// 先通过城市经理的城市id，在data中查找到对应的regoinid
	
			var regionId = 0;
			for(var i in data){
				if(data[i].cityId == userlogin.right_id){
					regionId = data[i].regionId;
					$("#pick_target").html(data[i].regionName);
					$("#pick_target").attr("data-id", data[i].regionId)
					$("#area").html(data[i].regionName);
					$("#area").attr("data-id", data[i].regionId)
					break;
				}
			}
			console.log(regionId)
			data = rd.subJson(data, "regionId", regionId); // 查到regoinid后，过滤data
		}
		// 定义
		var target_picker = new mui.PopPicker({layer:3});
	
		// 组织三级联选的json
		var target = [];
		if(! userlogin || userlogin.user_type != 12 ){ // 不是城市经理，都可以看到全国，大区总监（11）也能看到全国
			target.push({text:"全国", value: 0})
		}  
		var rgs = rd.distinct(data, 'regionName', 'regionId');
		for(var i in rgs){
			var rgdata = {};
			rgdata.text = i;
			rgdata.value = rgs[i];
			rgdata.children = [];
			rgdata.children.push({text: i, value: rgs[i]})
			var citys = rd.distinct(rd.subJson(data, "regionName", i), "cityName", "cityId");
			for(var j in citys){
				var cityData = {};
				cityData.text = j;
				cityData.value = citys[j];
				cityData.children = [];
				cityData.children.push({text: j, value: citys[j]})
				var gyms = rd.distinct(rd.subJson(data, "cityName", j), "gymName", "gymId");
				for(var k in gyms){
					var gymData = {};
					gymData.text = k;
					gymData.value = gyms[k];
					cityData.children.push(gymData);
				}
				rgdata.children.push(cityData);
			}
			target.push(rgdata);
		}
		target_picker.setData(target);
	
		// 三级联选点击事件
		$("#pick_target").on("tap", function(e){
			var self = $(this)
			console.log(self)
			target_picker.show(function(items){
				var rs = null;
				if(items[2].text && items[2].value != items[1].value){
					rs = items[2];
					vm.target_type = "gym";
				}else if(items[1].text && items[1].value != items[0].value){
					rs = items[1];
					vm.target_type = "city";
				}else{
					rs = items[0];
					vm.target_type = "region";
				}
				console.log(rs.text)
				vm.target_name = rs.text;
				vm.pick_target = rs.value;
				
			});
		});
	}, 'json');
}